using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using Citrix.WorkflowStudio.Common;
using Citrix.WorkflowStudio.CustomActivities.Designers;
using Citrix.WorkflowStudio.CustomActivities.Editors;
using Citrix.WorkflowStudio.CustomActivities.Serializers;
using Citrix.WorkflowStudio.User;

namespace Citrix.WorkflowStudio.Activities.WFSDatabaseActivities
{
	#region Attribute Definitions and Comments
    [Designer(typeof(BaseActivityDesigner))]
    [DisplayNameAttribute(@"SQL Database Connection")]
    [Description(@"This activity will provide a connection to a given sql server.")]
    [ActivityTreePath(@"Data/SQL Server")]
    [ActivityValidator(typeof(SQLConnectionValidator))]
	[ToolboxBitmapAttribute(typeof(SQLConnection), @"Resources.SQLConnection16.png")]
	[BaseActivityDesigner(ImageResourceName = @"Resources.SQLConnection32.png", AssemblyType = typeof(SQLConnection))]
	#endregion Attribute Definitions and Comments

	public partial class SQLConnection : ActivityBase
	{
		#region Constructor
		public SQLConnection()
		{
			InitializeComponent();
		}
		#endregion Constructor

        public static DependencyProperty ConnectionStringProperty = DependencyProperty.Register("ConnectionString", typeof(String), typeof(SQLConnection));
        [DefaultValue("server=localhost;database=maddison;uid=sa=pwd=maddison;")]
        [Category(@"Connection Information")]
        [DisplayName(@"ConnectionString")]
        [Description(@"The connection string to the SQL Database (Example: server=localhost;database=mydb;uid=sa;pwd=password).")]
        [Browsable(true)]
        [InputAttribute]
        [EditorAttribute(typeof(TextEditor), typeof(UITypeEditor))]
        public String ConnectionString
        {
            get
            {
                return ((String)(base.GetValue(ConnectionStringProperty)));
            }
            set
            {
                base.SetValue(ConnectionStringProperty, value);
            }
        }

        public static DependencyProperty ConnectionProperty = DependencyProperty.Register("Connection", typeof(System.Data.SqlClient.SqlConnection), typeof(SQLConnection));
        [Category(@"Connection Objects")]
        [DisplayName(@"SQL Connection Object")]
        [Description(@"SQL Connection object to be used with other activities.")]
        [ReadOnly(true)]
        [OutputAttribute]
        [BindTypes(new Type[] { typeof(System.Data.SqlClient.SqlConnection) })]
        [Browsable(true)]
        public System.Data.SqlClient.SqlConnection Connection
        {
            get
            {
                return (System.Data.SqlClient.SqlConnection)base.GetValue(ConnectionProperty);
            }
            set
            {
                base.SetValue(ConnectionProperty, value);
            }
        }

		// The logic for your activity belongs in the Execute method below
		#region Activity Execution Logic
		protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
		{
			// Expand all string properties with the required attribute
			ExpandStringProperties(executionContext.Activity);

			try
			{
                System.Data.SqlClient.SqlConnection _conn = new System.Data.SqlClient.SqlConnection(this.ConnectionString);
                this.Connection = _conn;

			}

			catch (Exception e)
			{
				String errmsg = "An error has occurred. The error is \"" + e.Message.ToString() + "\"";

				if (e.InnerException != null && e.InnerException.ToString().Length > 0)
					errmsg += "\nAdditional error info: \"" + e.InnerException.ToString() + "\"";

				throw new Exception(errmsg);

				// NOTE: Do not set ActivityExecutionStatus to Faulting if you throw an exception manually.
			}

			// You need to conclude your Execute method by setting the ActivityExecutionStatus.
			// Valid values are:
			//	Canceling
			//	Closed
			//	Compensating
			//	Executing
			//	Faulting
			//	Initialized
			return ActivityExecutionStatus.Closed;
		}
		#endregion Activity Execution Logic
	}

	// Property validation code
	//     In the Validate method you have to create a new instance of the activity class above,
	//     create a new ValidationErrorCollection instance, and then write the code to process the validation.
	//     For each validation error/warning, you need to add the error/warning to the ValidationErrorCollection.
	//     Finally, the Validate method should return the ValidationErrorCollection object.
	#region Validation Logic
	public class SQLConnectionValidator : ActivityValidator
	{
		public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
		{
			SQLConnection MyActivity = obj as SQLConnection;
			ValidationErrorCollection errs = new ValidationErrorCollection();
            
			if ((MyActivity != null) && (MyActivity.Parent != null))
			{
			// You can either set validation warnings or errors.
			//     To set a warning, pass 'true' for the 3rd parameter to errs.Add.
                	//     To set an error, pass 'false' for the 3rd parameter to errs.Add.

			#region Sample Property Validation
	        if (MyActivity.ConnectionString == null || MyActivity.ConnectionString.Length == 0)
                errs.Add(new ValidationError(@"You should specify a value for the 'ConnectionString' property.", 101, false, @"ConnectionString"));
			#endregion Sample Property Validation
			}
            
			#region StopOnError Validation
        	        if (!MyActivity.StopOnError)
	                {
        	            Boolean found = false;
	                    if (MyActivity.Activities != null)
        	            {
                	        for (int i = 0; ((i < MyActivity.Activities.Count) && (!found)); i++)
                        	{
	                            if (MyActivity.Activities[i].GetType() == typeof(System.Workflow.ComponentModel.FaultHandlersActivity))
        	                    {
                	                found = true;
                        	        CompositeActivity faultHandlers = (CompositeActivity)(MyActivity.Activities[i]);
                                	if ((faultHandlers.Activities == null) || (faultHandlers.Activities.Count == 0))
	                                    errs.Add(new ValidationError("The 'Stop On Error' property is set to 'false' but the auto-generated faultHandlerActivity has been manually deleted.", 101, false, "StopOnError"));
        	                    }
                	        }
                        	if (!found)
	                            errs.Add(new ValidationError("The 'Stop On Error' property is set to 'false' but the auto-generated faultHandlersActivity has been manually deleted.", 101, false, "StopOnError"));
        	            }
                	}
			#endregion StopOnError Validation

            
			// Return the ValidationErrorCollection
			return errs;
		}
	}
	#endregion Validation Logic
}
